package contact;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import entities.Contact;

public class ContactDAOImplement implements ContactDAO {

	private SessionFactory sf;

	public void setSf(SessionFactory sf) {
		this.sf = sf;
	}

	@Override
	public List<Contact> listContact() {
		// TODO Auto-generated method stub
		return sf.getCurrentSession().createCriteria(Contact.class).list();
	}

	@Override
	public Contact getById(int id) {
		// TODO Auto-generated method stub
		return (Contact) sf.getCurrentSession().get(Contact.class, id);
	}

	@Override
	public List<Contact> getByName(String firstName, String lastName) {
		// TODO Auto-generated method stub
		try {
			List<Contact> list = sf.getCurrentSession().createCriteria(Contact.class)
					.add(Restrictions.eq("firstname", firstName).ignoreCase())
					.add(Restrictions.eq("lastname", lastName).ignoreCase())
					.list();
			return list;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public List<Contact> getByFirstName(String firstName) {
		// TODO Auto-generated method stub
		try {
			List<Contact> list = sf.getCurrentSession()
					.createCriteria(Contact.class)
					.add(Restrictions.like("firstname", firstName + "%").ignoreCase()).list();
			return list;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

	@Override
	public boolean saveOrUpdate(Contact contact) {
		// TODO Auto-generated method stub
		try {
			sf.getCurrentSession().saveOrUpdate(contact);
			return true;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return false;
		}
	}

	@Override
	public List<Contact> getByAge(int age) {
		// TODO Auto-generated method stub
		try {
			List<Contact> list = sf.getCurrentSession()
					.createCriteria(Contact.class)
					.add(Restrictions.eq("age", age)).list();
			return list;
		} catch (HibernateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
	}

}
